package com.anycc.cloud.core.service.impl;

import com.anycc.cloud.common.dto.easyui.Tree;
import com.anycc.cloud.common.dto.query.PagingRequest;
import com.anycc.cloud.common.dto.query.PagingResponse;
import com.anycc.cloud.common.exception.AnyccRuntimeException;
import com.anycc.cloud.core.entity.Org;
import com.anycc.cloud.core.entity.OrgType;
import com.anycc.cloud.core.repository.OrgRepository;
import com.anycc.cloud.core.repository.OrgTypeRepository;
import com.anycc.cloud.core.service.OrgService;
import com.anycc.cloud.core.service.OrgTypeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * orgType service impl
 */
@Service
public class OrgTypeServiceImpl implements OrgTypeService {
    @Autowired
    private OrgTypeRepository orgTypeRepository;
    @Autowired
    private OrgRepository orgRepository;

    @Override
    public List<OrgType> findAllOrderByNameAsc() {
        return orgTypeRepository.findAll(Sort.by(Sort.Direction.ASC,"name"));
    }

    @Override
    public OrgType create(OrgType orgType) {
        checkName(orgType);
        return orgTypeRepository.save(orgType);
    }

    @Override
    public OrgType update(OrgType orgType) {
        checkName(orgType);
        return orgTypeRepository.save(orgType);
    }

    @Override
    public void delete(String id) {
        if (orgRepository.countByTypeId(id) > 0L) {
            throw new AnyccRuntimeException("core.exceptions.org.type.delete_has_org");
        } else {
            orgTypeRepository.deleteById(id);
        }
    }

    private void checkName(OrgType orgType) {
        if (orgType != null && !StringUtils.isBlank(orgType.getName())) {
            OrgType dbOrgType = orgTypeRepository.findByName(orgType.getName());
            if (dbOrgType != null && !StringUtils.equals(dbOrgType.getId(), orgType.getId())) {
                throw new AnyccRuntimeException("core.exceptions.org.type.name_existed,name=" + orgType.getName());
            }
        } else {
            throw new AnyccRuntimeException("core.exceptions.org.type.name_required");
        }
    }
}
